package com.guaju.yueshangLife.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.githang.statusbar.StatusBarCompat;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.activity.NetErrorActivity;
import com.guaju.yueshangLife.bean.MeBean;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.utils.AppManager;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.widget.EmptyView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscription;

import rx.subscriptions.CompositeSubscription;

import java.lang.reflect.Field;


//import com.umeng.messag.PushAgent;

/**
 *
 */
public abstract class BaseActivity extends Activity {

    protected Context mContext;
    private CompositeSubscription mCompositeSubscription;
    protected Subscription mSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            getWindow().setStatusBarColor(getResources().getColor(R.color.white));
            StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white));
        }

        AppManager.getAppManager().addActivity(this);

        //initGestureDetector();
        mContext = this;
//        ButterKnife.bind(this);
//        if (SharedPreferencesMgr.getInt(ConstanceValue.SP_THEME, ConstanceValue.THEME_LIGHT) == ConstanceValue.THEME_LIGHT) {
        setTheme(R.style.Theme_Light);
//        } else {
//            setTheme(R.style.Theme_Night);
//        }
        //获取夜间模式
//        mSubscription = toObservable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Notice>() {
//            @Override
//            public void call(Notice message) {
//                if (message.type == ConstanceValue.MSG_TYPE_CHANGE_THEME)
//                    ColorUiUtil.changeTheme(getWindow().getDecorView(), getTheme());
//            }
//
//        });

        setLayoutInflaterFactory();

        registerReceiver();

        initView(savedInstanceState);


        /**
         *此方法与统计分析sdk中统计日活的方法无关！请务必调用此方法！
         *如果不调用此方法，不仅会导致按照"几天不活跃"条件来推送失效，
         *还将导致广播发送不成功以及设备描述红色等问题发生。
         *可以只在应用的主Activity中调用此方法，但是由于SDK的日志发送策略，
         *有可能由于主activity的日志没有发送成功，而导致未统计到日活数据。
         */
//        PushAgent.getInstance(BaseActivity.this).onAppStart();
    }

    /** 手势监听 */
//    GestureDetector mGestureDetector;

    /**
     * 是否需要监听手势关闭功能
     */
//    private boolean mNeedBackGesture = false;
//
//    private void initGestureDetector() {
//        if (mGestureDetector == null) {
//            mGestureDetector = new GestureDetector(getApplicationContext(),
//                    new BackGestureListener(this));
//        }
//    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
//        if(mNeedBackGesture){
//            return mGestureDetector.onTouchEvent(ev) || super.dispatchTouchEvent(ev);
//        }
        return super.dispatchTouchEvent(ev);
    }

    /*
     * 设置是否进行手势监听
     */
    public void setNeedBackGesture(boolean mNeedBackGesture) {
//        this.mNeedBackGesture = mNeedBackGesture;
    }

    /*
     * 返回
     */
    public void doBack(View view) {
        onBackPressed();
    }

    public void setLayoutInflaterFactory() {
        LayoutInflater layoutInflater = getLayoutInflater();
        try {
            Field mFactorySet = LayoutInflater.class.getDeclaredField("mFactorySet");
            mFactorySet.setAccessible(true);
            mFactorySet.set(layoutInflater, false);
//            LayoutInflaterCompat.setFactory(layoutInflater, new SkinFactory(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    public RecyclerView initCommonRecyclerView(BaseQuickAdapter adapter, RecyclerView.ItemDecoration decoration) {
//        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//        return initCommonRecyclerView(recyclerView, adapter, decoration);
//    }
//
//    public RecyclerView initCommonRecyclerView(RecyclerView recyclerView, BaseQuickAdapter adapter, RecyclerView.ItemDecoration decoration) {
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        if (decoration != null) {
//            recyclerView.addItemDecoration(decoration);
//        }
//        recyclerView.setAdapter(adapter);
//        return recyclerView;
//    }
//
//    public RecyclerView initHorizontalRecyclerView(BaseQuickAdapter adapter, RecyclerView.ItemDecoration decoration) {
//        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
//        if (decoration != null) {
//            recyclerView.addItemDecoration(decoration);
//        }
//        recyclerView.setAdapter(adapter);
//        return recyclerView;
//    }
//
//    public RecyclerView initGridRecyclerView(int resId, BaseQuickAdapter adapter, RecyclerView.ItemDecoration decoration, int spanCount) {
//        RecyclerView recyclerView = (RecyclerView) findViewById(resId == 0 ? R.id.recyclerView : resId);
//        recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount));
//        if (decoration != null) {
//            recyclerView.addItemDecoration(decoration);
//        }
//        recyclerView.setAdapter(adapter);
//        return recyclerView;
//    }
//
//    public RecyclerView initGridRecyclerView(BaseQuickAdapter adapter, RecyclerView.ItemDecoration decoration, int spanCount) {
//        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//        recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount));
//        if (decoration != null) {
//            recyclerView.addItemDecoration(decoration);
//        }
//        recyclerView.setAdapter(adapter);
//        return initGridRecyclerView(0, adapter, decoration, spanCount);
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterHomeWatcherReceiver();
        overridePendingTransition(R.anim.hold, R.anim.slide_right_exit);
        AppManager.getAppManager().finishActivity(this);

    }

    /**
     * 初始化界面
     */
    protected void initView(Bundle savedInstanceState) {
        loadViewLayout();
        bindViews();
        if (NetworkUtil.isConnected(this)) {
            processLogic(savedInstanceState);
        } else {
            showNetError();
        }
        setListener();
    }

//    protected void showLog(String log) {
//        Logger.i(log);
//    }


    /**
     * 获取控件
     *
     * @param id  控件的id
     * @param <E>
     * @return
     */
    protected <E extends View> E get(int id) {
        return (E) findViewById(id);
    }

    /**
     * 加载布局
     */
    protected abstract void loadViewLayout();

    /**
     * find控件
     */
    protected abstract void bindViews();


    /**
     * 处理数据
     */
    protected abstract void processLogic(Bundle savedInstanceState);

    /**
     * 设置监听
     */
    protected abstract void setListener();

    /**
     * 界面跳转
     *
     * @param tarActivity
     */
    protected void intent2Activity(Class<? extends Activity> tarActivity) {
        Intent intent = new Intent(mContext, tarActivity);
        startActivity(intent);
    }

    /**
     * 显示Toast
     *
     * @param msg
     */
    protected void showToast(String msg) {
//        ToastUtils.showToast(msg);
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 注册事件通知
     */
//    public Observable<Notice> toObservable() {
//        return RxBus.getDefault().toObservable(Notice.class);
//    }

    /**
     * 发送消息
     */
//    public void post(Notice msg) {
//        RxBus.getDefault().post(msg);
//    }

    //RXjava取消注册，以避免内存泄露
//    public void onUnsubscribe() {
//        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
//            mCompositeSubscription.unsubscribe();
//        }
//    }

//    public void addSubscription(Observable observable, Subscriber subscriber) {
//        if (mCompositeSubscription == null) {
//            mCompositeSubscription = new CompositeSubscription();
//        }
//        mCompositeSubscription.add(observable
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber));
//    }
    public void firstBaseActivtyResume() {

    }

    protected boolean isRunCYJStatInterfaceRecordPageStart = false;

    @Override
    protected void onResume() {
        super.onResume();

        firstBaseActivtyResume();
        numIndexHome = 0;

        if (isRunCYJStatInterfaceRecordPageStart == false) {
//            CYJStatInterface.recordPageStart(BaseActivity.this);
        }

        Glide.with(BaseApplication.getInstance()).resumeRequests();
//        MobclickAgent.onResume(this);
//        Session.onResume(this);
        if (BaseApplication.getInstance().isRetryable()) {
            processLogic(null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

//        if(isRunCYJStatInterfaceRecordPageStart == false){
//            CYJStatInterface.recordPageEnd();
//        }

        Glide.with(BaseApplication.getInstance()).pauseRequests();
//        MobclickAgent.onPause(this);
//        Session.onPause(this);
    }

    private HomeWatcherReceiver mHomeWatcherReceiver = null;
    private static int numIndexHome = 0;

    protected void registerReceiver() {
        mHomeWatcherReceiver = new HomeWatcherReceiver();
        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mHomeWatcherReceiver, filter);
    }


    public class HomeWatcherReceiver extends BroadcastReceiver {

        private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
        private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {

            String MyAPP = "HomeWatcherReceiver";

            Log.i(MyAPP, "numIndexHome =" + numIndexHome);

            if (numIndexHome > 0) {
                return;
            }

            String intentAction = intent.getAction();

            Log.i(MyAPP, "intentAction =" + intentAction);
            if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                Log.i(MyAPP, "reason =" + reason);
                if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) {

                    numIndexHome++;

                    //closeApp();
                    //CYJStatInterface.recordPageEnd();

                }
            }
        }

    }

    public void unregisterHomeWatcherReceiver() {
        if (mHomeWatcherReceiver != null) {
            try {
                unregisterReceiver(mHomeWatcherReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void closeApp() {

//        CYJStatInterface.recordAppEnd(EXIT_APP_ACTION);
//        ReportDataUtil.reportAllData();
//        JCVideoPlayer.releaseAllVideos();
        AppManager.getAppManager().finishAllActivity();

//        MyIntentService.destroyTimer();

    }

    //    private ExitAppReceiver exitReceiver = new ExitAppReceiver();
    //自定义退出应用Action,实际应用中应该放到整个应用的Constant类中.
    public static final String EXIT_APP_ACTION = "com.cyj.exit_app";

    protected void sendExitBeceiver() {

        Intent intent = new Intent();
//        intent.setAction(MainActivity.EXIT_APP_ACTION);
        mContext.sendBroadcast(intent);

    }


    protected void registerExitReceiver() {

        IntentFilter exitFilter = new IntentFilter();
        exitFilter.addAction(EXIT_APP_ACTION);
//        registerReceiver(exitReceiver, exitFilter);


    }

    protected void unRegisterExitReceiver() {

//        unregisterReceiver(exitReceiver);
    }

    public void showNetError() {
        if (!NetworkUtil.isConnected(this)) {
            if ((!(this instanceof NetErrorActivity)) && (!BaseApplication.getInstance().isFinishable())) {
                startActivity(new Intent(this, NetErrorActivity.class));

            }
        }
    }

    public void showEmpty() {
        View decorView = getWindow().getDecorView();
        FrameLayout contentParent =
                (FrameLayout) decorView.findViewById(android.R.id.content);
        EmptyView emptyView = new EmptyView(BaseActivity.this);
        contentParent.addView(emptyView);
        ToastUtil.show("数据为空，请稍后重试");
    }



}
